package com.hp.springboot.service;

import com.hp.springboot.dao.UserDao;
import com.hp.springboot.dao.UserOrderDao;
import com.hp.springboot.pojo.model.User;
import com.hp.springboot.pojo.model.UserOrder;
import java.math.BigDecimal;
import java.util.Date;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 测试Service
 *
 * @author hupan
 * @date 2021-11-14 21:25
 */
@Slf4j
@Service
public class TestService {

    @Resource
    private UserDao userDao;
    @Resource
    private UserOrderDao userOrderDao;
    @Resource
    private UserOrderService userOrderService;

    @Transactional(rollbackFor = Exception.class)
    public void testTransactional1() {
        User user = new User();
        user.setName("TestTransactional1");
        user.setAge(16);
        user.setGender(1);
        user.setIdCard("421127");
        user.setMobile("15611111111");
        user.setAddress("BaoAnXiXiang");
        user.setCreateTime(new Date());

        UserOrder userOrder = new UserOrder();
        userOrder.setOrderNo("TestTransactional-001");
        userOrder.setUserId(user.getId());
        userOrder.setPayAmount(new BigDecimal("1000"));
        userOrder.setTotalAmount(new BigDecimal("1000"));
        userOrder.setDeliveryAddr("盐田新二村131号");
        userOrder.setStatus((byte) 0);
        userOrder.setCreateTime(new Date());

        userDao.saveUser(user);
        // 直接获取插入的ID --> 可以正常获取
        userOrder.setUserId(user.getId());
        userOrderDao.saveUserOrder(userOrder);

        userOrderService.testGetOrderById(userOrder.getId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void testTransactional2() {
        User user = new User();
        user.setName("TestTransactional2");
        user.setAge(26);
        user.setGender(1);
        user.setIdCard("421127");
        user.setMobile("15622222222");
        user.setAddress("BaoAnXiXiang");
        user.setCreateTime(new Date());

        UserOrder userOrder = new UserOrder();
        userOrder.setOrderNo("TestTransactional-002");
        userOrder.setUserId(user.getId());
        userOrder.setPayAmount(new BigDecimal("1000"));
        userOrder.setTotalAmount(new BigDecimal("1000"));
        userOrder.setDeliveryAddr("盐田新二村131号");
        userOrder.setStatus((byte) 0);
        userOrder.setCreateTime(new Date());

        userDao.saveUser(user);
        userOrder.setUserId(user.getId());
        userOrderDao.saveUserOrder(userOrder);

        userOrderService.testGetOrderById(userOrder.getId());
    }

}
